﻿#pragma once

/**
 * 串口业务封装类
 * 使用时请继承本类，并实现dataHandle方法
 */
#include <QObject>
#include <QThread>
#include "AsCoreGlobal.h"

class AsSerialPortDataHandleWork;
class QSerialPort;
class AS_CORE_EXPORT AsSerialPort  : public QObject {

public:
	AsSerialPort(QObject *parent = nullptr);
	~AsSerialPort();

	inline void setPortName(QString portName) { m_qsPortName = portName; }
	inline void setBaudRate(int baudRate) { m_iBaudRate = baudRate; }		//设置波特率

	void open();
	void sendData(const QByteArray& data);

	void sendHexData(const QByteArray& hexData);
protected:
	virtual void dataHandle(const QByteArray& data);			//数据处理

private:

	QThread m_hThread;
	AsSerialPortDataHandleWork* m_pWork;
	int m_iBaudRate;
	QString m_qsPortName;

	friend class AsSerialPortDataHandleWork;
};

//异步处理
class AsSerialPortDataHandleWork : public QObject
{
	Q_OBJECT
public:
	AsSerialPortDataHandleWork(AsSerialPort* serialPort);

	void setPortNameAndBaudRate(QString portName,int baudRate);
	
	bool isOpen();
public slots:
	void close();
	void onRecevieData();
	void actionOpen();
	void onSendData(QByteArray data);

private:
	QSerialPort* m_pPort;
	AsSerialPort* m_pAsPort;
};